<!--
 * @Description:角色管理
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-22 11:41:57
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-21 14:37:09
-->
<template>
  <div class="systemRole z-w-100">
    <tableSearch
      ref="tableSearch"
      :item-data="itemData"
      :button-data="buttonData"
      :column-data="columnData"
      :api="findPageRole"
      :cb="cb"
      @click="btnClick"
    >
      <template
        slot="rStatus"
        slot-scope="{ row, props }"
      >
        <el-tag
          v-if="row[props] && row[props].length > 0"
          :type="row[props] === '1' ? 'success' : 'warning'"
          size="small"
        >
          {{ changeLabel(statusData, row[props]) }}
        </el-tag>
      </template>

      <template
        slot="userId"
        slot-scope="{ row, props }"
      >
        {{ changeArrTolabel(userData, row[props]) }}
      </template>

      <template
        slot="mid"
        slot-scope="{ row, props }"
      >
        {{ row[props].map(v=>v.mName).join(",") }}
      </template>
      <template
        slot="action"
        slot-scope="{ row }"
      >
        <ButtonConfig
          :button-data="actionData"
          :row="row"
          @click="actionClick"
        />
      </template>
    </tableSearch>
    <baseDialog
      ref="baseDialog"
      :befor-comfire="beforComfire"
      :title="cTitle"
    >
      <template slot="content">
        <el-scrollbar
          class="scrollbarCls is-horizontal--none"
        >
          <Form
            ref="Form"
            :key="refreshFromKey"
            v-model="initFormData"
            :item-data="formData"
            :rules="rules"
            :form-config="formConfig"
          />
        </el-scrollbar>
      </template>
    </baseDialog>
  </div>
</template>

<script>
import tableSearch from '@/components/tableSearch/index.vue'
import { itemData, columnData, buttonData } from './data.js'
import { findPageRole, getAllUser, updateRole, addRole } from '@/api/role.js'
import { changeLabel, changeArrTolabel, getListToRules } from '@/utils/index.js'
import baseDialog from '@/components/baseDialog/index.vue'
import ButtonConfig from '@/components/ButtonConfig/index.vue'
import Form from '@/components/Form/index.vue'
import { formData } from './formData'
export default {
  name: 'SystemRole',
  components: {
    tableSearch,
    ButtonConfig,
    baseDialog,
    Form
  },
  data () {
    return {
      itemData,
      columnData,
      buttonData,
      statusData: [
        { label: '启用', value: '1' },
        { label: '未启用', value: '0' }
      ],
      userData: [],
      actionData: [
        { type: 'text', text: '修改', actionType: 'update' },
        { type: 'text', text: '查看', actionType: 'view' }
        // { type: 'text', text: '删除', actionType: 'delete' }
      ],
      formData,
      rules: {},
      initFormData: {},
      refreshFromKey: 1,
      actionType: 'add',
      formConfig: {
        disabled: false,
        hideRequiredAsterisk: false
      }
    }
  },
  computed: {
    cTitle () {
      const map = {
        add: '新增用户',
        view: '查看用户',
        update: '修改用户'
      }
      return map[this.actionType]
    }
  },
  created () {
    this.getAllUserFun()
  },
  methods: {
    cb (data) {
      return data.map(v => {
        if (!v.userId || v.userId === '') {
          v.userId = ''
        }
        const target = v.userId.split(',')
        this.$set(v, 'userId', target)
        return v
      })
    },
    async beforComfire () {
      const access = this.$refs.Form.validator()
      const isAdd = this.actionType === 'add'
      if (access) {
        const data = this.$refs.Form.form
        const res = isAdd ? await addRole(data) : await updateRole(data)
        if (res.code === '0') {
          this.$message.success('操作成功')
          this.$refs.tableSearch.refreshList()
        }
        return true
      }
      console.log(isAdd)
      return false
    },
    findPageRole,
    changeLabel,
    changeArrTolabel,
    // 设置默认数据
    setDefaultFormData (data) {
      this.initFormData = {}
      for (const key in data) {
        this.$set(this.initFormData, key, data[key])
      }
    },
    // 设置弹窗状态 新增 修改
    setDialogStatus (data) {
      this.refreshFromKey++ // 刷新表单
      this.rules = getListToRules(formData) // 把formData数据转换成为rules数据
      this.setDefaultFormData(data) // 设置默认显示的数据
      // this.setItemSelectData() // 设置表单下拉的数据
      this.$refs.baseDialog.show() // 弹窗显示
      this.$nextTick(() => {
        const targetKeys = Object.keys(this.rules)
        this.$refs.Form.clearValidate(targetKeys) // 清除上次错误信息
      })
    },
    async setUserIdOptionsData (row) {
      await this.getAllUserFun()
      let disabled = false
      const targetUserId = this.formData.find(v => v.props === 'userId')
      const optionsData = this.userData.map(v => {
        if (row.rid === v.rid) {
          disabled = false
        } else {
          if (v.rid === '0' || !v.rid) {
            disabled = false
          } else {
            disabled = true
          }
        }
        const json = {
          ...v,
          disabled
        }
        return json
      })
      if (targetUserId) {
        this.$set(targetUserId.config, 'options', optionsData)
      }
    },
    async actionClick (item, row) {
      await this.setUserIdOptionsData(row)
      this.actionType = item.actionType
      this.rules = getListToRules(formData)
      this.setreeDialogConfig(row) // 设置弹窗参数
      if (item.actionType === 'update') {
        console.log(row, 'rowrow')
        this.$set(this.formConfig, 'disabled', false)
        this.$set(this.formConfig, 'hideRequiredAsterisk', false)
        this.setDialogStatus(row) // 设置弹窗状态 新增 修改
      } else if (item.actionType === 'delete') {
        this.$set(this.formConfig, 'hideRequiredAsterisk', false)
        this.handleDelete(row.id)
      } else if (item.actionType === 'view') {
        this.$set(this.formConfig, 'disabled', true)
        this.$set(this.formConfig, 'hideRequiredAsterisk', true)
        this.setDialogStatus(row)
      }
    },
    // 设置弹窗参数
    setreeDialogConfig (row) {
      const targetTreeDialog = this.formData.find(v => v.props === 'mid')
      if (targetTreeDialog) {
        this.$set(targetTreeDialog.config, 'params', { role: row.rid })
      }
    },
    async btnClick (item) {
      if (item.actionType === 'refresh') {
        this.$refs.tableSearch.refreshList()
      } else if (item.actionType === 'add') {
        await this.setUserIdOptionsData({})
        this.actionType = item.actionType
        this.$set(this.formConfig, 'disabled', false)
        this.$set(this.formConfig, 'hideRequiredAsterisk', false)
        const data = {
          rStatus: '1'
        }
        this.setDialogStatus(data) // 设置弹窗状态 新增 修改
      }
    },
    async getAllUserFun () {
      const result = await getAllUser()
      if (result.code === '0') {
        this.userData = result.data.map((v) => {
          const json = {
            value: v.userId,
            label: v.userName,
            ...v
          }
          return json
        })
      }
    }
  }
}
</script>

<style></style>
